<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of StoriesController
 *
 * @author Zoila
 */
class UploadsController extends AppController{
    
    //AUTORIZACION
    public function isAuthorized($user) {
        // All registered users can add posts
        if (in_array($this->action, array('uploadFile', 'add','download','createFolder','delete'))) {
            return true;
        }

        // The owner of a post can edit and delete it
        if (in_array($this->action, array('delete','deleteFolder'))) {
            $stId = $this->request->params['pass'][0];
            if ($this->Upload->isOwnedBy($stId, $user['id'])) {
                return true;
            }
                return true;
        }

        return parent::isAuthorized($user);
    }
    
    function uploadFile() {
        if ($this->request->data!=null){
            
            $idProject=$this->request->data['Upload']['project_id'];
            $idFolder=$this->request->data['Upload']['folder_id'];
            $file = $this->request->data['Upload']['file'];
//            var_dump($file);
            if ($file['error']  === UPLOAD_ERR_OK) {
                $this->request->data['Upload']['filename'] = substr($file['name'], 0, strrpos($file['name'], '.'));
                $this->request->data['Upload']['fileextension'] = substr(strrchr($file['name'], '.'), 1);
                $this->request->data['Upload']['filesize'] = $file['size'];
                $this->request->data['Upload']['filemime'] = $file['type'];
                $this->request->data['Upload']['creator_id'] = $this->Auth->user('id');
                $id=String::uuid();
                $this->request->data['Upload']['name'] = $id;
                unset($this->request->data['Upload']['file']);
                if ($this->Upload->save($this->request->data) ) {
                    
                    if(move_uploaded_file($file['tmp_name'], APP.'uploads'.DS.$id)){
                        $this->Session->setFlash('Su archivo se subió con éxito');
                    }
                    else {$this->Session->setFlash('Ha ocurrido un error al subir su archivo');var_dump($this->request->data);}
                }
                else {$this->Session->setFlash('Error al guardar en la BD');}
                $url='../projects/repository/'.$idProject;
                if($idFolder!=0)
                    $url.='/'.$idFolder;
                $this->redirect($url);
//                $this->redirect(array('controller'=>'projects','action'=>'repository',$idProject));
            }
            return false;
        }
    }
    
    function createFolder() {
        if ($this->request->data!=null){
            $idProject=$this->request->data['Upload']['project_id'];
            $idFolder=$this->request->data['Upload']['folder_id'];
            $this->request->data['Upload']['creator_id'] = $this->Auth->user('id');
            $this->request->data['Upload']['project_id'] = $idProject;
            if ($this->Upload->save($this->request->data) ) {
                $this->Session->setFlash('Su creó el folder con éxito');
            }
            else {
                $this->Session->setFlash('Error en crear el folder');
                
                }
            $url='../projects/repository/'.$idProject;
            if($idFolder!=0)
                $url.='/'.$idFolder;
            $this->redirect($url);
        }
    }
    
    function delete($id,$fromView=0){
        $upload = $this->Upload->find('first', array(
		'conditions' => array(
			'Upload.id' => $id)));
        $url="../projects/repository/".$upload['Upload']['project_id'].'/'.$upload['Upload']['folder_id'];
        $file=$upload['Upload']['name'];
        $filename=$upload['Upload']['filename'];
        if ($file==""){
            $uploads = $this->Upload->find('all', array(
		'conditions' => array(
			'Upload.folder_id' => $id)));
            foreach((array)$uploads as $u){ 
                $this->delete($u['Upload']['id']);
            }
            if ($this->Upload->delete($id)&& ($fromView==1)) {
                $this->Session->setFlash('Se eliminó la carpeta : ' . $filename . ' ');
                $this->redirect($url);
            }
        }
        else{
            if ($this->Upload->delete($id)&& ($fromView==1) ) {
                unlink(APP.'uploads'.DS.$file);
                $this->Session->setFlash('The File: ' . $filename . ' has been deleted.');
                $this->redirect($url);
            }
        }
    }
    function deleteFolder ($id){
        $upload = $this->Upload->find('first', array(
		'conditions' => array(
			'Upload.id' => $id)));
        $url="../projects/repository/".$upload['Upload']['project_id'].'/'.$upload['Upload']['folder_id'];
        $file=$upload['Upload']['name'];
        if ($this->Upload->delete($id)) {
            unlink(APP.'uploads'.DS.$file);
            $this->Session->setFlash('The File: ' . $file . ' has been deleted.');
            $this->redirect($url);
        }
    }
    
    
    function download($id = null) {
	if (!$id) {
		$this->Session->setFlash(__('Invalid id for upload', true));
		$this->redirect(array('controller' => 'users','action' => 'view',$this->Auth->user('id')));
	}
//	$this->Upload->bindModel(array('hasOne' => array('UploadsUser')));
	$upload = $this->Upload->find('first', array(
		'conditions' => array(
			'Upload.id' => $id
//                        'Upload.user_id' => $this->Auth->user('id')
//			'OR' => array(
//				'UploadsUser.user_id' => $this->Auth->user('id'),
//				'Upload.user_id' => $this->Auth->user('id'),
//			),
		)
	));
	if (!$upload) {
		$this->Session->setFlash(__('Invalid id for upload', true));
		$this->redirect(array('action' => 'index'));
	}
	$this->viewClass = 'Media';
	$this->set(array(
		'id' => $upload['Upload']['name'],
		'name' => $upload['Upload']['filename'],
		'extension' => $upload['Upload']['fileextension'],
		'path' => APP.'uploads'.DS,
		'download' => true,
	));
    }   
    
}

?>
